import pool from '../db/index.js'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'

export async function Sign(req,res){
    try {
        
        const {username,password,email}=req.body
        const saltRounds = 10;
        const password_hash=await bcrypt.hash(password,saltRounds);

        const [result]=await pool.query(
            'INSERT INTO users (username,password_hash,email) VALUES(?,?)',
            [username,password_hash,email]
        );

        return res.status(200).json({
            code:200,
            msg:'注册成功',
            data:result.insertId
        })

    } catch (error) {
        return res.status(500).json('服务器错误，注册失败')
    }
}

export async function LogIn(req,res){
    try {
        const {username,password}=req.body;
        const [logUser]= await pool.query(
            'SELECT * FROM users WHERE username=?',
            [username]
        )
        
        const passwordValid = await bcrypt.compare(password,logUser[0].password_hash);

        if(!passwordValid){
            return res.status(401).json('用户名或者密码不正确')
        }
        
        const token=jwt.sign(
            {userId:logUser[0].id , email:logUser[0].email},
            process.env.JWT_SECRET,
            {expiresIn:process.env.JWT_EXPIRES_IN}
        )

        return res.status(200).json({
            code:200,
            msg:`欢迎你,${logUser[0].username}`,
            data:{
                token:token,
                UserInfo:{
                    id:logUser[0].id,
                    username:logUser[0].username,
                    email:logUser[0].email,
                    created_at:logUser[0].created_at
                }

            }
        })
    } catch (error) {
       return res.status(500).json(error.message)
    }
}

export async function LogOut(req,res){
    try{
        const token =req.headers.authorization?.split(' ')[1];
        const decoded=jwt.verify(token,process.env.JWT_SECRET);
        const now=Date.now() / 1000;
        const expiresIn=decoded.exp-now;

        if(expiresIn>0){
            tokenBlackList[token]=true;
            setTimeout(() => {
                delete tokenBlackList[token]
            }, expiresIn*1000);
        }

        return res.status(200).json({
            code:200,
            msg:'成功退出登录',
            data:{
                message:'success'
            }
        })

    }catch(error){
        return res.status(500).json(error.message)
    }
    
}